package com.g17.virtualpetbackend.service;

import com.g17.virtualpetbackend.entity.Paper;
import com.g17.virtualpetbackend.entity.User;
import com.g17.virtualpetbackend.repo.PaperRepository;
import com.g17.virtualpetbackend.repo.UserRepository;
import org.neo4j.driver.internal.value.FloatValue;
import org.neo4j.driver.internal.value.PathValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PaperService {

    @Resource
    private PaperRepository paperRepository;

    @Resource
    private UserRepository userRepository;

    private static Logger logger = LoggerFactory.getLogger(PaperService.class);

    public Paper createPaper(String question_ids) {
        Paper paper = paperRepository.createPaper();
        String[] questionIds = question_ids.split(",");
        for (String questionId: questionIds) {
            paperRepository.linkPaperAndQuestion(paper.getId(), Long.valueOf(questionId));
        }
        return paper;
    }

    public List<Paper> getAllPapers() {
        return paperRepository.findAll();
    }

    public Paper distributePaperToStudent(Long paperId, String[] usernames, String time) {
//        paperRepository.unlinkPaperAndAllUser(paperId);
        Paper paper = paperRepository.findPaperById(paperId);
        for (String username:usernames) {
            paperRepository.linkPaperAndUser(paperId, username, time);
        }
        return paper;
    }

    public List<User> getAttendedUserByPaper(Long paperId) {
        return userRepository.getAttendedUserByPaper(paperId);
    }

    public List<Paper> getAttendPaperByUser(String username) {
        List<Paper> paperList = paperRepository.findAllPaperByUsername(username);
        for (Paper paper:paperList) {
            PathValue pathValue = paperRepository.findRelationshipByNodes(username, paper.getId()).get(0);
            String time = pathValue.asPath().relationships().iterator().next().get("time").toString();
            paper.setTime(time);
        }
        return paperList;
    }

    public Long deleteUserToPaper(Long paperId, String username) {
        paperRepository.unlinkPaperAndUser(paperId, username);
        List<Paper> paperList = paperRepository.findAllPaperByUsername(username);
        if (paperList.contains(paperRepository.findPaperById(paperId))) {
            return (long) -1;
        }
        return paperId;
    }

    public Float insertScore(Long paperId, String username, Float score) {
        FloatValue scoreFinal = paperRepository.setScore(paperId, username, score).get(0);
        paperRepository.setHasTest(paperId, username);
        return scoreFinal.asFloat();
    }
}
